package com.jse;

import java.lang.System.Logger.Level;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;

public class Log {

	private final static Map<String,Log> CACHE=new HashMap<>();
	
	public String name="Log";
	public void setName(String name) {this.name = name;}
	public String getName() {return name;}
	
	private static Level level=Level.TRACE;
	
	public Log() {}
	public Log(String name) {this.name=name;}
	public static Log get(String name) {
		if(CACHE.containsKey(name))return CACHE.get(name);
		Log log=new Log(name);CACHE.put(name, log);
		return log;}
	public static Log get(Class<?> c) {return get(c.getName());}
	public static Log getLogger(Class<?> c) {return get(c);}
	
	public boolean isLoggable(Level lv) {return lv.compareTo(level)>-1;}
	
	public void trace(String s,Object...args) {out(Level.TRACE,s,args);}
	public void debug(String s,Object...args) {out(Level.DEBUG,s,args);}
	public void info(String s,Object...args) {out(Level.INFO,s,args);}
	public void warn(String s,Object...args) {out(Level.WARNING,s,args);}
	public void error(String s,Object...args) {out(Level.ERROR,s,args);}
	public void log(Object s,Object...args) {debug(s.toString(),args);}
	
	public void out(Level level,String s,Object...args) {
		if(!isLoggable(level))return;
		if(args!=null&&args.length>0)s=s.replace("{}","%s").formatted(args);
		if(s.length()>0&&s.charAt(0)=='#') {
			System.out.println(s);
		}else {
			var time=Instant.now().toString().substring(0,23);//Thread.currentThread().threadId() tid
			String str="%s (%s) PID:%s [%s] [%s]:%s".formatted(time,Jse.name,Jse.pid,level.name(),name,s);
			switch (level) {
			case Level.TRACE ->print(35,str);
			case Level.DEBUG ->print(32,str);
			case Level.INFO ->print(36,str);
			case Level.WARNING ->print(33,str);
			case Level.ERROR ->print(31,str);
			case Level.OFF ->print(37,str);
			case Level.ALL ->print(42,str);
			}
		}
	}
	
	public static void log(Level level,String s,Object...args) {
		get(Jse.name).out(level, s, args);
	}
	
//  \33[32;4m表示改变字体
//  \33[0m 变回原样
//  // 背景颜色代号(41-46)
//  // 前景色代号(31-36)
//  //前景色代号和背景色代号可选，就是可以写，也可以不写
//  // 数字+m：1加粗；3斜体；4下划线
//  // 格式：System.out.println("\33[前景色代号;背景色代号;数字m");
//  System.out.format("\33[32;4m我是博主\33[0m%n");//%n表示换行
//	for (int i = 31; i < 48; i++) {
//		print(i+"==",i,1,rs.getObject(1)+","+rs.getObject(2));//%n表示换行
//	}
//	for (int i = 90; i < 99; i++) {
//		print(i+"==",i,1,rs.getObject(1)+","+rs.getObject(2));//%n表示换行
//	}
	public static void print(int code,String s){System.out.format("\33[%d;1m%s\33[0m%n",code,s);}
	public static void print(String s){int colors=Lang.rand(3,4)*10+Lang.rand(1,7);System.out.format("\33[%d;1m%s\33[0m%n",colors,s);}
	
	public static void main(String[] args) {
		
	}
}
